def merge(intervals):
    intervals.sort()
    result = []
    mins = intervals[0][0]
    maxs = intervals[0][1]
    for i in range(1, len(intervals)):
        if intervals[i][0] <= mins and intervals[i][1] <= maxs:
            mins = intervals[i][0]
        elif intervals[i][0] >= mins and intervals[i][1] >= maxs and intervals[i][0] <= maxs:
            maxs = intervals[i][1]
        elif intervals[i][0] <= mins and intervals[i][1] >= maxs:
            mins = intervals[i][0]
            maxs = intervals[i][1]
        elif intervals[i][0] >= maxs:
            result.append([mins, maxs])
            mins = intervals[i][0]
            maxs = intervals[i][1]
    result.append([mins, maxs])
    return result

if __name__ == "__main__":
    merge([[1, 3], [2, 6], [8, 10], [15, 18]])